package com.yzh.zhipu.session;

import com.yzh.zhipu.ChatGlmApi;
import com.yzh.zhipu.executor.Executor;
import com.yzh.zhipu.executor.impl.GlmExecutor;
import com.yzh.zhipu.executor.impl.GlmOldExecutor;
import com.yzh.zhipu.model.vo.Model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSources;

import java.util.HashMap;

@Data
@Slf4j
@AllArgsConstructor
@NoArgsConstructor
public class Configuration {
    private String apiHost;         //请求地址
    private String apiSecretKey;    //API秘钥(需要拆分)
    private String apiKey;          //拆分后的API Key
    private String apiSecret;       //拆分后的API 秘钥
    private OkHttpClient okHttpClient;  //Http客户端
    private ChatGlmApi chatGlmApi;      //retrofit2的API
    private HttpLoggingInterceptor.Level level = HttpLoggingInterceptor.Level.HEADERS;  //日志(影响响应速度)
    private long connectTimeout = 450;      //连接超时时间，45s内未建立连接则超时
    private long writeTimeout = 450;        //写入超时时间，即客户端向服务器发送请求数据的最长等待时间
    private long readTimeout = 450;         //读取超时时间，即客户端从服务器接收响应数据的最长等待时间
    //HTTP参数配置
    public static final String SSE_CONTENT_TYPE = "text/event-stream";
    public static final String DEFAULT_USER_AGENT = "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)";
    public static final String APPLICATION_JSON = "application/json";
    public static final String JSON_CONTENT_TYPE = APPLICATION_JSON + "; charset=utf-8";
    
    
    /**
     * 用来创建Factory对象，通过Factory工厂创建EventSource流式传输对象（OkHTTP提供）
     * @return
     */
    public EventSource.Factory createRequestFactory() {
        return EventSources.createFactory(okHttpClient);
    }

    /**
     * ChatGLM需要将apiSecretKey根据".“拆分为二
     * 后续会将apiKey作为载荷，secretKey作为秘钥生成JWT携带请求模型接口
     * @param apiSecretKey
     */
    public void splitSecretKey(String apiSecretKey) {
        this.apiSecretKey = apiSecretKey;
        String[] split = apiSecretKey.split("\\.");
        if (split.length != 2) {
            throw new RuntimeException("Api密钥错误");
        }
        this.apiKey = split[0];
        this.apiSecret = split[1];
    }

    /**
     * 根据不同模型选择不同的执行器
     */
    private HashMap<Model, Executor> executorMap;
    public HashMap<Model, Executor> createExecutorMap() {
        this.executorMap = new HashMap<>();
        //旧版模型
        GlmOldExecutor glmOldExecutor = new GlmOldExecutor(this);
        executorMap.put(Model.CHATGLM_TURBO, glmOldExecutor);
        //新版模型
        GlmExecutor glmExecutor = new GlmExecutor(this);
        executorMap.put(Model.GLM_3_TURBO, glmExecutor);
        executorMap.put(Model.GLM_4, glmExecutor);
        executorMap.put(Model.GLM_4V, glmExecutor);
        executorMap.put(Model.COGVIEW_3, glmExecutor);
        return executorMap;
    }
    
}
